import $api from '@/api/index';
import { ref } from 'vue';


let infoData = {
  info: null,
  buttons: null,
}


// 状态
// 0 初始化
// 1 请求中
// 2 请求完成
// 3 错误
// let status = 0

// 请求数据
const reqUserInfoHandle = async function () {
  try {
    user.status.value = 1
    const result = await $api.user.reqUserInfo()
    if (result?.data?.code === 200) {
      user.status.value = 2
      Object.assign(infoData, {
        info: result.data.data,
        buttons: result.data.data.buttons
      })

      return 'ok'
    } else {
      throw new Error(result?.data?.message)
    }

  } catch (error) {
    user.status.value = 3
    return Promise.reject(error.message)
  }
}

// 请求数据
const removeUserInfoHandle = async function () {
  user.status.value = 0

  infoData = {
    info: null,
    buttons: null,
  }

}

export const user = {
  infoData,
  status: ref(0),
  async getInfo() {
    if (user.status.value !== 2) {
      await reqUserInfoHandle()
    }
    return infoData
  },

  async resize() {
    await removeUserInfoHandle()
  }
}